﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WO.GCode
{
    class GUniqueCode
    {
        private static readonly object lockTimeCode = new object();
        private static Dictionary<string, int> dic = new Dictionary<string, int>();

        public List<string> GSeqTimeCode(string preCode="",int pCount=1)
        {
            List<string> tmLs = new List<string>();
                 int secondCount = 1;
                 StringBuilder sb = new StringBuilder();

            for (int i = 0; i < pCount; i++)
            {
                sb.Clear();
                string timeCode = preCode+DateTime.Now.ToString("yyyyMMddHHmmss");
                sb.Append(timeCode);
           
                lock (lockTimeCode)
                {
                    if (!dic.ContainsKey(timeCode))
                    {
                        if (dic.Count > 10)//定期清除内存
                            dic.Clear();
                        secondCount = 1;
                        dic.Add(timeCode, 1);
                    }
                    else
                    {
                        if (dic[timeCode] >= 9999)//同个时间如果生成的序号数超过9999,将等待下一秒继续生成编号
                        {
                          while(timeCode ==DateTime.Now.ToString("yyyyMMddHHmmss"))
                          {
                              Thread.Sleep(0);
                          }
                          continue;
                        }
                        dic[timeCode]++;
                        secondCount = dic[timeCode];
                    }

                    string strNo = secondCount.ToString().PadLeft(4, '0');
                    sb.Append(strNo);
                    tmLs.Add(sb.ToString());
                }
            }

            return tmLs;
        }
    }
}
